<?php

namespace app\modules\setting\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "basic_user".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $crt_name
 * @property string $crt_time
 */
class User extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'basic_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password', 'crt_name', 'crt_time'], 'required'],
            [['crt_time'], 'safe'],
            [['username'], 'string', 'max' => 15],
            [['password'], 'string', 'max' => 16],
            [['crt_name'], 'string', 'max' => 10],
            ['username', 'validateUsername'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户ID',
            'username' => '用户名',
            'password' => '管理员密码',
            'crt_name' => '创建人',
            'crt_time' => '创建时间',
        ];
    }

    public function validateUsername($attribute)
    {
        if (($model = $this::findOne(['username' => $this->username])) !== null) {
            $this->addError($attribute, '用户名重复。');
        }
    }

    public function checkUsername()
    {
        if ($this->validate()) {
            return true;
        }
        return false;
    }

    public function login()
    {
        $model = $this::findOne(['username' => $this->username]);
        if (!empty($model) && Yii::$app->getSecurity()->decryptByKey(base64_decode($model->password), Yii::$app->params['encryptKey']) == $this->password) {
            return true;
        }
        return false;
    }

    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            $this->password = base64_encode(Yii::$app->getSecurity()->encryptByKey($this->password, Yii::$app->params['encryptKey']));
            return true;
        } else {
            return false;
        }
    }

    public function getUserPermissions()
    {
        return $this->hasOne(UserPermissions::className(), ['user_id' => 'user_id']);
    }
}
